package com.md.api.common.utils;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.toList;

public class ListUtil {

//    public static List<String> list = Arrays.asList("1","2","2","3","3","4","4","5","6","7","8");
//    public static List<City> cities = null;
//    static {
//        cities = new ArrayList<City>(){
//            {
//                add(new City("上海",11));
//                add(new City("武汉",22));
//                add(new City("武汉",55));
//                add(new City("上海",33));
//                add(new City("北京",33));
//                add(new City("深圳",43));
//            }
//        };
//
//    }
//    public static void main(String[] args) {
//        System.out.println(ListUtil.distinctElements(list));
//        System.out.println(ListUtil.getNoDuplicateElements(list));
//        System.out.println(ListUtil.getDuplicateElements(list));
//        System.out.println(ListUtil.getDuplicateElementsForObject(cities));
//        System.out.println(ListUtil.getNoDuplicateElementsForObject(cities));
//        System.out.println(ListUtil.getElementsAfterDuplicate(cities));
//        System.out.println(ListUtil.getDuplicateObject(cities));
//        System.out.println(ListUtil.getNoDuplicateObject(cities));
//        System.out.println(ListUtil.distinctObject(cities));
//    }

    // 交集
    public void jiaoji(List<String> list1,List<String> list2){
        List<String> intersection = list1.stream().filter(item ->   list2.contains(item)).collect(toList());
        System.out.println("---交集 intersection---");
        intersection.parallelStream().forEach(System.out :: println);
    }

    // 差集 (list1 - list2)
    public void chaji(List<String> list1,List<String> list2){
        List<String> reduce1 = list1.stream().filter(item -> !list2.contains(item)).collect(toList());
        System.out.println("---差集 reduce1 (list1 - list2)---");
        reduce1.parallelStream().forEach(System.out :: println);
    }

    // 差集 (list2 - list1)
    public void chajito(List<String> list1,List<String> list2){
        List<String> reduce2 = list2.stream().filter(item -> !list1.contains(item)).collect(toList());
        System.out.println("---差集 reduce2 (list2 - list1)---");
        reduce2.parallelStream().forEach(System.out :: println);
    }

    // 并集
    public void binji(List<String> list1,List<String> list2){
        List<String> listAll = list1.parallelStream().collect(toList());
        List<String> listAll2 = list2.parallelStream().collect(toList());
        listAll.addAll(listAll2);
        System.out.println("---并集 listAll---");
        listAll.parallelStream().forEachOrdered(System.out :: println);
    }

    // 去重并集
    public void quchongjiaoji(List<String> list1,List<String> list2){
        List<String> listAll = list1.parallelStream().collect(toList());
        List<String> listAll2 = list2.parallelStream().collect(toList());
        listAll.addAll(listAll2);
        List<String> listAllDistinct = listAll.stream().distinct().collect(toList());
        System.out.println("---得到去重并集 listAllDistinct---");
        listAllDistinct.parallelStream().forEachOrdered(System.out::println);
    }

    //去重后的集合 [1, 2, 3, 4, 5, 6, 7, 8]
    public static <T> List<T> distinctElements(List<T> list) {
        return list.stream().distinct().collect(toList());
    }

    //lambda表达式 去除集合重复的值  [1, 5, 6, 7, 8]
    public static <T> List<T> getNoDuplicateElements(List<T> list) {
        // 获得元素出现频率的 Map，键为元素，值为元素出现的次数
        Map<T, Long> map = list.stream().collect(Collectors.groupingBy(p -> p,Collectors.counting()));
        System.out.println("getDuplicateElements2: "+map);
        return map.entrySet().stream() // Set<Entry>转换为Stream<Entry>
                .filter(entry -> entry.getValue() == 1) // 过滤出元素出现次数等于 1 的 entry
                .map(entry -> entry.getKey()) // 获得 entry 的键（重复元素）对应的 Stream
                .collect(toList()); // 转化为 List
    }

    //lambda表达式 查找出重复的集合 [2, 3, 4]
    public static <T> List<T> getDuplicateElements(List<T> list) {
        return list.stream().collect(Collectors.collectingAndThen(Collectors
                .groupingBy(p -> p, Collectors.counting()), map->{
            map.values().removeIf(size -> size ==1); // >1 查找不重复的集合；== 1 查找重复的集合
            List<T> tempList = new ArrayList<>(map.keySet());
            return tempList;
        }));
    }

    //利用set集合
    public static <T> Set<T> getDuplicateElements2(List<T> list) {
        Set<T> set = new HashSet<>();
        Set<T> exist = new HashSet<>();
        for (T s : list) {
            if (set.contains(s)) {
                exist.add(s);
            } else {
                set.add(s);
            }
        }
        return exist;
    }

    /**-----------对象List做处理--------------*/

    //查找对象中某个原属重复的  属性集合   [上海, 武汉]
//    public static List<String> getDuplicateElementsForObject(List<City> list) {
//        return list.stream().collect(Collectors.groupingBy(p -> p.getCity(),Collectors.counting())).entrySet().stream()
//                .filter(entry -> entry.getValue() > 1) // >1 查找重复的集合；== 查找不重复的集合
//                .map(entry -> entry.getKey())
//                .collect(toList());
//    }

    //查找对象中某个原属未重复的  属性集合   [深圳, 北京]
//    public static List<String> getNoDuplicateElementsForObject(List<City> list){
//        Map<String,List<City>> map = list.stream().collect(Collectors.groupingBy(City::getCity));
//        return map.entrySet().stream().filter(entry -> entry.getValue().size() == 1)
//                .map(entry -> entry.getKey()) // 获得 entry 的键（重复元素）对应的 Stream
//                .collect(toList()); // 转化为 List
//
//    }

    //查找对象中某个原属去重后的集合 [上海, 武汉, 北京, 深圳]
//    public static List<String> getElementsAfterDuplicate(List<City> list) {
//        return list.stream().map(o->o.getCity()).distinct().collect(toList());
//    }

    //对象中某个原属重复的 对象集合
    // [[City(city=上海, total=11), City(city=上海, total=33)], [City(city=武汉, total=22), City(city=武汉, total=55)]]
//    public static List<List<City>> getDuplicateObject(List<City> list) {
//        return list.stream().collect(Collectors.groupingBy(City::getCity)).entrySet().stream()
//                .filter(entry -> entry.getValue().size() > 1) // >1 查找重复的集合；== 查找不重复的集合
//                .map(entry -> entry.getValue())
//                .collect(toList());
//    }
//
//    //对象中某个原属未重复 对象集合
//    //[[City(city=深圳, total=43)], [City(city=北京, total=33)]]
//    public static List<City> getNoDuplicateObject(List<City> list) {
//        List<City> cities = new ArrayList<>();
//        list.stream().collect(Collectors.groupingBy(City::getCity)).entrySet().stream()
//                .filter(entry -> entry.getValue().size() ==1) //>1 查找重复的集合；== 查找不重复的集合;
//                .map(entry -> entry.getValue())
//                .forEach(p -> cities.addAll(p));
//        return cities;
//    }


    //根据对象的某个原属去重后的 对象集合
    //[City(city=上海, total=11), City(city=武汉, total=22), City(city=北京, total=33), City(city=深圳, total=43)]
//    public static List<City> distinctObject(List<City> list) {
//        return list.stream().filter(distinctByKey(City::getCity)).collect(toList());
//    }

    public static <T> Predicate<T> distinctByKey(Function<? super T, Object> keyExtractor) {
        Map<Object, Boolean> seen = new ConcurrentHashMap<>();
        return object -> seen.putIfAbsent(keyExtractor.apply(object), Boolean.TRUE) == null;
    }

    //list排序 正序
    public static <T> List<T> sort(List<T> list){
        return list.stream().sorted().collect(toList());
    }

    //list排序 倒序
    public static List<Integer> reversed(List<Integer> list){
        return list.stream().sorted(Comparator.reverseOrder()).collect(toList());
    }

    //根据对象某个属性排序  正序
//    public static List<City> sortForObject(List<City> list){
//        return list.stream().sorted(Comparator.comparing(City::getTotal)).collect(toList());
//    }

    //根据对象某个属性排序  倒序
//    public static List<City> reversedForObject(List<City> list){
//        return list.stream().sorted(Comparator.comparing(City::getTotal).reversed()).collect(toList());
//    }

    //根据对象两个属性排序  正序
//    public static List<City> sortForObject2(List<City> list){
//        return list.stream().sorted(Comparator.comparing(City::getTotal).thenComparing(City::getNum)).collect(toList());
//    }
    //根据对象某个属性求各自值
    ///IntSummaryStatistics{count=4, sum=132, min=11, average=33.000000, max=55}
    public static IntSummaryStatistics calculation(List<Integer> list){
        IntSummaryStatistics stat = list.stream().collect(Collectors.summarizingInt(p -> p));
        System.out.println("max:"+stat.getMax());
        System.out.println("min:"+stat.getMin());
        System.out.println("sum:"+stat.getSum());
        System.out.println("count:"+stat.getCount());
        System.out.println("average:"+stat.getAverage());
        Integer max = list.stream().reduce(Integer::max).get();//得到最大值
        Integer min = list.stream().reduce(Integer::min).get();//得到最小值
        System.out.println("max:"+max+"；min:"+min);
        return stat;
    }

    //功能描述 字符串转list
    public static void stringToList(String str){
        //不需要处理
        //<String> list = Arrays.asList(str.split(","));
        //需要处理
        List<String> list = Arrays.asList(str.split(",")).stream().map(string -> String.valueOf(string)).collect(toList());
        list.forEach(string -> System.out.println(string));
    }


    //功能描述 姓名以逗号拼接
    public static void joinStringValueByList2(List<String> list){
        //方式一
        System.out.println(String.join(",", list));
        //方式二
        System.out.println(list.stream().collect(Collectors.joining(",")));
    }

}
